import 'package:bitcoin_mine/common/global.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/app_config.dart';
import '../routes/app_routes.dart';

class PrivacyController extends GetxController {
  // 隐私协议同意状态
  final RxBool hasAgreedToPrivacy = false.obs;

  // 是否显示隐私协议弹窗
  final RxBool showPrivacyDialog = false.obs;

  // 本地存储键
  static const String _privacyAgreementKey = 'privacy_agreement_accepted';

  @override
  void onInit() {
    super.onInit();
    _checkPrivacyAgreementStatus();
    // requestTrackingAuthorization();
  }

  /// 检查隐私协议同意状态
  Future<void> _checkPrivacyAgreementStatus() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final hasAgreed = prefs.getBool(_privacyAgreementKey) ?? false;

      print('隐私协议状态检查: hasAgreed = $hasAgreed');

      hasAgreedToPrivacy.value = hasAgreed;

      // 如果用户还没有同意隐私协议，显示弹窗
      if (!hasAgreed) {
        print('用户未同意隐私协议，设置显示弹窗');
        showPrivacyDialog.value = true;
      } else {
        print('用户已同意隐私协议，隐藏弹窗');
        showPrivacyDialog.value = false;
      }
    } catch (e) {
      print('检查隐私协议状态错误: $e');
      // 如果出错，默认显示弹窗
      showPrivacyDialog.value = true;
    }
  }

  /// 用户同意隐私协议
  Future<void> agreeToPrivacy() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_privacyAgreementKey, true);

      hasAgreedToPrivacy.value = true;
      showPrivacyDialog.value = false;

      await Global.initApp();
    } catch (ignore) {}
  }

  /// 用户不同意隐私协议
  void disagreeToPrivacy() {
    Get.snackbar(
      '提示',
      '您必须同意隐私政策才能继续使用应用',
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 3),
    );

    // 可以选择退出应用或保持弹窗显示
    // 这里我们保持弹窗显示，让用户重新选择
  }

  /// 打开隐私政策链接
  void openPrivacyPolicy() {
    Get.toNamed(
      AppRoutes.webView,
      arguments: {'url': AppConfig.privacyPolicyUrl, 'title': '隐私政策'},
    );
  }

  /// 打开服务条款链接
  void openTermsOfService() {
    Get.toNamed(
      AppRoutes.webView,
      arguments: {'url': AppConfig.userAgreementUrl, 'title': '用户协议'},
    );
  }
}
